package weapp

import (
	"github.com/medivhzhan/weapp/v2"
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/miniprogram/auth"
	"github.com/silenceper/wechat/v2/miniprogram/config"
)

var memory *cache.Memory = cache.NewMemory()

//小程序登录
func Login(app_id, secret, code string) (*auth.ResCode2Session, error) {
	//res, err := weapp.Login(app_id, secret, code)
	//if err != nil {
	//	// 处理一般错误信息
	//
	//	return nil, err
	//}
	//
	//if err := res.GetResponseError(); err != nil {
	//	// 处理微信返回错误信息
	//	return nil, err
	//}
	//
	//return res, nil
	wc := wechat.NewWechat()
	cfg := &config.Config{
		AppID:     app_id,
		AppSecret: secret,
		Cache:     memory,
	}

	mini := wc.GetMiniProgram(cfg)
	a := mini.GetAuth()
	resp, err := a.Code2Session(code)
	if err != nil {
		return nil, err
	}
	return &resp, nil

}

func GetAccessToken(app_id, secret string) (*weapp.TokenResponse, error) {
	res, err := weapp.GetAccessToken(app_id, secret)
	if err != nil {
		// 处理一般错误信息
		return nil, err
	}

	if err := res.GetResponseError(); err != nil {
		// 处理微信返回错误信息
		return nil, err
	}

	return res, nil
}

func GetPaidUnionID() {
	res, err := weapp.GetPaidUnionID("access-token", "open-id", "transaction-id")
	// 或者
	//res, err := weapp.GetPaidUnionIDWithMCH("access-token", "open-id", "out-trade-number", "mch-id")

	if err != nil {
		// 处理一般错误信息
		return
	}

	if err := res.GetResponseError(); err != nil {
		// 处理微信返回错误信息
		return
	}

}
